package com.quanyan.ic.vendingMachine.protocol.client;

import com.quanyan.ic.vendingMachine.protocol.codec.protobuf.VmMessageProto;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufEncoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32LengthFieldPrepender;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.net.InetSocketAddress;


/**
 * Created by zhuo.shi on 2017/5/27.
 */
public class Client {

    private static Logger logger = LoggerFactory.getLogger(Client.class);

    private Bootstrap bootstrap;

    private ThreadLocal<Channel> channelThreadLocal = new ThreadLocal<Channel>();

    public ChannelFuture start(String host, int port) {
        NioEventLoopGroup group = new NioEventLoopGroup(0);
        if (bootstrap == null) {
            bootstrap = new Bootstrap();
        }
        bootstrap.group(group)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new ProtobufVarint32FrameDecoder());
                        pipeline.addLast(new ProtobufDecoder(VmMessageProto.VmMessage.getDefaultInstance()));
                        pipeline.addLast(new ProtobufVarint32LengthFieldPrepender());
                        pipeline.addLast(new ProtobufEncoder());
                        pipeline.addLast(new HandShakeReqHandler());

                    }
                });
        try {
            ChannelFuture f = bootstrap.connect(new InetSocketAddress(host, port));
            if (f.isSuccess()) {
                channelThreadLocal.set(f.channel());
            }
            logger.info("lark IC client started");
            f.channel().closeFuture().sync();
            return f;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
        return null;
    }

    public Channel getChannel() {
        return channelThreadLocal.get();
    }

    public static void main(String[] args) {
        Client client = new Client();
        ChannelFuture f = client.start("localhost", 9263);
    }
}
